package com.gewu.advertisement.core.model

import android.util.Log

/**
 * 广告播放队列
 * @author htt 2021/1/11
 */
class AdvertisingQueue {


    private val tag = "AdvertisingQueue"
    private var advertsements = mutableListOf<Advertising>()

    //当前资源
    private var currentAdvertising: Advertising? = null

    //当前资源的播放次数
    private var currentPlayCount = 0

    fun submit(list: List<Advertising>) {
        this.advertsements = list.toMutableList()
        currentAdvertising = null
        currentPlayCount = 0
    }

    /**
     * 获取下一个播放资源
     */
    fun next(): Advertising? {
        if (advertsements.isEmpty()) return null
        val advertising = if (currentAdvertising == null) { //第一次播放
            advertsements.firstOrNull() ?: return null
        } else { //有已经播放过的资源
            val currentAdvertising = this.currentAdvertising!!
            if (currentAdvertising in advertsements && currentPlayCount < currentAdvertising.videoPlayTimes) {
                //资源没有被删除并且播放次数还没达到限制
                currentAdvertising
            } else {
                //资源已被删除或者播放次数已经达到限制
                var index = advertsements.indexOf(currentAdvertising) + 1
                if (index >= advertsements.size) index = 0
                currentPlayCount = 0
                advertsements[index]
            }
        }
        if (advertising.isExpire) {
            advertsements.remove(advertising)
            Log.i(tag, "资源已过期:$advertising")
            return next()
        }
        currentAdvertising = advertising
        currentPlayCount++
        return advertising
    }

    fun remove(advertising: Advertising) {
        advertsements.remove(advertising)
    }


    /**
     * 重置队列顺序
     */
    fun reset() {
        currentAdvertising = null
        currentPlayCount = 0
    }
}